package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.exception.BaseException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.nio.file.AccessDeniedException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Slf4j
@Service
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
     private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增菜品和对应口味
     *
     * @param dishDTO
     */
 @Transactional //事务，必须方法全部执行正确，有一个执行错误都不进行
    @Override
 @CacheEvict(cacheNames = "dish_cache",allEntries = true)
    public void save(DishDTO dishDTO) {
        //1.保存菜品基本信息
        Dish dish=new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        dish.setStatus(StatusConstant.DISABLE);//起始为停售
        dishMapper.insert(dish);

        //2.保存菜品口味信息
        List<DishFlavor> flavors = dishDTO.getFlavors();
        flavors.forEach(dishFlavor ->{
            dishFlavor.setDishId(dish.getId());//每一个口味赋值到菜品id上
                }
                );
        dishFlavorMapper.insertBatch(flavors);//批量保存菜品口味
    }

    /**
     * 菜品分页查询
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult page(DishPageQueryDTO dishPageQueryDTO) {
       //1.设置分页参数
        PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());

        //2.执行查询
        //Page <DishVO> page=dishMapper.list(dishPageQueryDTO);
        Page<DishVO> page = dishMapper.pageQuery(dishPageQueryDTO);
        //3.解析并封装结果
        //Page<DishVO> page= (Page<DishVO>) dishVOList;
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 批量删除菜品
     * @param ids
     */
    @Override
    @CacheEvict(cacheNames = "dish_cache",allEntries = true)
    public void delete(List<Long> ids) {

         //判断当前菜品是否能够删除---是否存在起售中的菜品？？提示错误信息
       Long count= dishMapper.countEnableDishByIds(ids);//拿出传过来的ids中是否有起售状态的菜品
        if(count>0){
            //这批菜品包含起售菜品
            throw new BaseException(MessageConstant.DISH_ON_SALE);
        }

        //判断当前菜品是否能够删除---是否被套餐关联了？？提示错误信息
            //去中间表查，查setmeal_id是否存在，存在即关联，存到List集合里
            List<Long> setmealIds=setmealDishMapper.getSetmealIdsByDishIds(ids);
        if(!CollectionUtils.isEmpty(setmealIds)){//不为空，即关联了套餐
            throw new BaseException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        //删除菜品表中的菜品数据，并删除菜品口味
        dishMapper.deleteByIds(ids);
        dishFlavorMapper.deleteByDishIds(ids);

    }

    /**
     * 根据id查询菜品数据用于页面回显
     * @param id
     * @return
     */
    @Override
    public DishVO getInfo(Long id) {
        //1.根据id查询菜品的基本信息--Dish
        Dish dish=dishMapper.getById(id);
        //2.根据id查询菜品口味信息--List<DishFlavor>
        List<DishFlavor> dishFlavorList=dishFlavorMapper.getByDishId(id);
        //3.组装数据
        DishVO dishVO=new DishVO();
        BeanUtils.copyProperties(dish,dishVO);

        if (dishVO!=null) {
            dishVO.setFlavors(dishFlavorList);
        }
        return dishVO;
    }

    /**
     * 修改菜品
     * @param dishDTO
     */
    @CacheEvict(cacheNames = "dish_cache",allEntries = true)
    @Override
    public void update(DishDTO dishDTO) {
        //1.根据id修改菜品基本信息 --Dish
        Dish dish=new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        dishMapper.update(dish);

        //2.根据id修改菜品口味信息 --dish-flavor（先删，后加）
        //先删
        dishFlavorMapper.deleteByDishIds(Collections.singletonList(dish.getId()));//把id转成list
        //在添加
        List<DishFlavor> flavors = dishDTO.getFlavors();//给每一个口味赋值上dishid
        flavors.forEach(dishFlavor -> {
            dishFlavor.setDishId(dish.getId());
        });
        dishFlavorMapper.insertBatch(flavors);
    }


    /**
     * 根据分类id查询菜品
     * @param categoryId
     * @return
*/

    @Override

public List<Dish> list(Long categoryId) {
    Dish dish = Dish.builder()
        .categoryId(categoryId)
        .status(StatusConstant.ENABLE)
        .build();
    return dishMapper.list(dish);
}

    @Override
    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */

    public List<DishVO> listWithFlavor(Dish dish) {
        /*Long categoryId = dish.getCategoryId();
        String redisDishKey="dish:cache"+categoryId;
        //1.先查询redis缓存，如果缓存中有数据，直接返回*//*
       List<DishVO> dishVOList = (List<DishVO>) redisTemplate.opsForValue().get(redisDishKey);
       if (!CollectionUtils.isEmpty(dishVOList)){
           log.info("查询redis缓存，命中数据，直接返回");
           return dishVOList;
       }*/
        //2.如果缓存中没有数据，在查询数据库

        List<Dish> dishList = dishMapper.list(dish);

      List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            Long id = d.getId();
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

       /* //3.把数据查询的结果，加入缓存
        redisTemplate.opsForValue().set(redisDishKey,dishVOList);
        log.info("查询数据库，将查询到的数据，缓存在redis中");*/
        return dishVOList;
    }

    /**
     * 菜品起售停售
     *
     * @param status
     * @param id
*/
@Transactional
@CacheEvict(cacheNames = "dish_cache",allEntries = true)
public void startOrStop(Integer status, Long id) {
    Dish dish = Dish.builder()
        .id(id)
        .status(status)
        .build();
    dishMapper.update(dish);

    if (status == StatusConstant.DISABLE) {
        // 如果是停售操作，还需要将包含当前菜品的套餐也停售
        List<Long> dishIds = new ArrayList<>();
        dishIds.add(id);
        // select setmeal_id from setmeal_dish where dish_id in (?,?,?)
        List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(dishIds);
        if (setmealIds != null && setmealIds.size() > 0) {
            for (Long setmealId : setmealIds) {
                Setmeal setmeal = Setmeal.builder()
                    .id(setmealId)
                    .status(StatusConstant.DISABLE)
                    .build();
                setmealMapper.update(setmeal);
            }
        }
    }
}
}
